import Vue from 'vue'
import VueRouter from 'vue-router'

//路由跳转引入
import Login from '@/views/Login'
import Home from '@/views/Home'
import Register from '@/views/Register'
import Search from '@/views/Search'
import Detail from '@/views/Detail'
import AddCartSuccess from '@/views/AddCartSuccess'
import Shopcart from '@/views/ShopCart'

//引用 vuex 仓库
import store from '@/store'

Vue.use(VueRouter)

//保存原型上的 push | replace 方法
let overRidePush=VueRouter.prototype.push;
let overRideReplace=VueRouter.prototype.replace;

//在原用的方法上 重写原型上的方法
VueRouter.prototype.push=function(location,resolve,reject) {
  if(resolve && reject){
    overRidePush.call(this,location,resolve,reject)
  }else{
    overRidePush.call(this,location,()=>{},()=>{})
  }
}

VueRouter.prototype.replace=function(location,resolve,reject) {
  if(resolve && reject){
    overRideReplace.call(this,location,resolve,rejcet)
  }else{
    overRideReplace.call(this,location,()=>{},()=>{})
  }
}

const routes = [
  {
    path:"/",
    redirect: '/home'
  },
  {
    path: '/home',
    component: Home,
    //footer 显示与隐藏
    meta:{showFooter:true}
  },
  {
    path: '/trade',
    component: ()=> import ('@/views/Trade'),
    //footer 显示与隐藏
    meta:{showFooter:true}
  },
  {
    path: '/login',
    component: Login,
    meta:{showFooter:false}
  },
  {
    path:'/register',
    component:Register,
    meta:{showFooter:false}
  },
  {
    //  /:Search?  是params传递参数的占位 ？是可选的
    path:'/search/:keyword?',
    component:Search,
    name:'searchName',
    meta:{showFooter:true},
     // 将params参数和query参数映射成属性传入路由组件
     props: route => ({keyword3: route.params.keyword, keyword4: route.query.keyword2})
  },
  {
    path:'/detail/:skuid',
    name:'Detail',
    component:Detail,
    meta:{showFooter:true}
  },
  //添加商品
  {
    path:'/addcartsuccess',
    name:'addCartSuccess',
    component:AddCartSuccess,
    meta:{showFooter:true}
  },
  //购物车详情
  {
    path:'/shopcart',
    component:Shopcart,
    meta:{showFooter:true}
  },
  //支付页面
  {
    path:'/pay',
    component:()=>import('@/views/Pay'),
    meta:{showFooter:true}
  },
  //支付成功
  {
    path:'/paysuccess',
    component:()=>import('@/views/PaySuccess'),
    meta:{showFooter:true}
  },
  //我的订单
  {
    path: '/center',
    component: ()=>import('@/views/Center'),
    children: [
      {
        // path: '/center/myorder',
        path: 'myorder',
        component: ()=>import('@/views/Center/myOrder'),
      },
      {
        path: 'groupbuy',
        component:  ()=>import('@/views/Center/groupOrder'),
      },
      {
        path: '',
        redirect: 'myorder'
      }
    ]
  }
 
  
]

const router = new VueRouter({
  mode: 'history',
  routes
})

//全局前置守卫
router.beforeEach(async (to, from, next) => {
  // to: Route: 即将要进入的目标 路由对象
  // from: Route: 当前导航正要离开的路由
  // next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数
 
  //先获取有没有token  可以知道登录没
  let token = store.state.LoginAndLoginOut.token
  let UserName = store.state.LoginAndLoginOut.name
  console.log(token,UserName);
  //如果获取到了  自动转换true
  //已经登录的情况
  if(token){
    if (to.path == '/login' || to.path == '/register') {
      //如果登录  就不再允许去登录注册了
      next('/')
    }else{
      //已经登录 访问的不是登录 注册
      if(UserName){
        //如果有用户信息  就放行
        next()
      }else{
        //如果没有用户信息
        try {
          //获取用户信息
          await store.dispatch('getUserInfo')
          next()
        } catch (error) {
          //token 失效 退出登录  重新登录
          await store.dispatch('LoginOut')
          next('/login')
        }
      }
    }
  }else{
    //如果访问的是购物车 叫用户登录
    //未登录去上面这些路由-----登录
    let toPath = to.path;
    if(toPath.indexOf('/trade')!=-1 || toPath.indexOf('/pay')!=-1||toPath.indexOf('/center')!=-1){
      //把未登录的时候向去而没有去成的信息，存储于地址栏中【路由】
      next('/login?redirect='+toPath);
    }else{
       //去的不是上面这些路由（home|search|shopCart）---放行
       next();
    }
  }
})

export default router
